c++救助,"#include指令”嵌入其他文件出错?(在线)

来源:百度知道 编辑:UC知道 时间:2024/06/22 14:41:37
书上这道:
#inlcude"filename"格式用来引用用户自己定义的头文件,编译器从用户的工作目录开始搜索。
例如:
#include<stdio.h>
程序也允许嵌入其他文件,例如:
main()
{
#include<help.c>
}
其中help.c为另一个文件,内容可为
printf("glad to meet you here!");

我就这样编写的:

//2.cpp
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
#include "help.cpp"
return 0;
}

//help.cpp
#include "stdafx.h"
void test()
{
printf("gald to meet you here!");
}

可是出错:
“fatal error C1083: 无法打开包括文件:“help.cpp”: No such file or directory”

如果第二个文件"help.cpp",像书很哪样(printf语句没有加入一个函数里),出错更多:

1>正在编译...
1>2.cpp
1>g:\vc++9.0\2\2\2.cpp(7) : fatal error C1083: 无法打开包括文件:“help.cpp”: No such file or directory
1>help.cpp
1>g:\vc++9.0\1\1\help.cpp(4) : error C4430: 缺少类型说明符 - 假定为 int

你试试这么写

//2.cpp
#include "stdafx.h"
int main(int argc, _TCHAR* argv[])
{
#include "help.cpp"
return 0;
}

//help.cpp
printf("gald to meet you here!");

我认为书上是这个意思
main函数里面那个include就相当于help.cpp的内容

以上就相当于

#include "stdafx.h"
int main(int argc, _TCHAR* argv[])
{
printf("gald to meet you here!");
return 0;
}

宏替换,包含文件,条件编译是预处理的三大工作。
它们不是C++语言,是编译器命令,所以只能放在每个文件的开头,当然条件编译可以例外。

将2.cpp修改如下
//2.cpp
#include "help.cpp"
int _tmain(int argc, _TCHAR* argv[])
{
test();
return 0;
}

include 不能放到主函数里,要放到文件最开始

头文件要放在程序开头,
有文件可以定义变量,函数,常量
不能单独定义语句